import { Task } from '../types'

// 筛选条件接口
export interface FilterOptions {
  priorities: string[]      // 优先级筛选 ['P0', 'P1', 'P2', 'P3']
  categories: string[]      // 分类筛选 ['work', 'personal', 'learning', 'health', 'other']
  statuses: string[]        // 状态筛选 ['completed', 'pending', 'all']
  tags: string[]           // 标签筛选
  dateRange: string        // 日期范围 ['today', 'thisWeek', 'overdue', 'noDate', 'all']
}

// 排序选项
export type SortOption = 
  | 'priority'      // 按优先级排序
  | 'dueDate'       // 按截止日期排序
  | 'createdAt'     // 按创建时间排序
  | 'title'         // 按标题排序
  | 'status'        // 按完成状态排序

export type SortDirection = 'asc' | 'desc'

// 默认筛选条件
export const defaultFilterOptions: FilterOptions = {
  priorities: ['P0', 'P1', 'P2', 'P3'],
  categories: ['work', 'personal', 'learning', 'health', 'other'],
  statuses: ['pending'],
  tags: [],
  dateRange: 'all'
}

// 筛选任务
export function filterTasks(tasks: Task[], filters: FilterOptions): Task[] {
  return tasks.filter(task => {
    // 优先级筛选
    if (filters.priorities.length > 0 && !filters.priorities.includes(task.priority)) {
      return false
    }

    // 分类筛选
    if (filters.categories.length > 0 && !filters.categories.includes(task.category)) {
      return false
    }

    // 状态筛选
    if (filters.statuses.includes('completed') && !task.completed) {
      return false
    }
    if (filters.statuses.includes('pending') && task.completed) {
      return false
    }
    // 如果选择了'all'，则不过滤状态

    // 标签筛选
    if (filters.tags.length > 0) {
      const hasMatchingTag = filters.tags.some(tag => 
        task.tags.some(taskTag => taskTag.toLowerCase().includes(tag.toLowerCase()))
      )
      if (!hasMatchingTag) {
        return false
      }
    }

    // 日期范围筛选
    if (filters.dateRange !== 'all') {
      const now = new Date()
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 1)
      const weekStart = new Date(today)
      weekStart.setDate(today.getDate() - today.getDay()) // 本周开始
      const weekEnd = new Date(weekStart)
      weekEnd.setDate(weekStart.getDate() + 7) // 本周结束

      if (task.dueDate) {
        const taskDate = new Date(task.dueDate)
        const taskDateOnly = new Date(taskDate.getFullYear(), taskDate.getMonth(), taskDate.getDate())

        switch (filters.dateRange) {
          case 'today':
            if (taskDateOnly.getTime() !== today.getTime()) return false
            break
          case 'thisWeek':
            if (taskDateOnly < weekStart || taskDateOnly >= weekEnd) return false
            break
          case 'overdue':
            if (taskDateOnly >= today || task.completed) return false
            break
          case 'noDate':
            return false // 有日期的任务不符合"无日期"筛选
        }
      } else {
        // 无日期的任务
        if (filters.dateRange !== 'noDate') return false
      }
    }

    return true
  })
}

// 排序任务
export function sortTasks(tasks: Task[], sortBy: SortOption, direction: SortDirection = 'asc'): Task[] {
  const sortedTasks = [...tasks].sort((a, b) => {
    let comparison = 0

    switch (sortBy) {
      case 'priority':
        // P0 > P1 > P2 > P3 (数字越小优先级越高)
        const priorityOrder = { 'P0': 0, 'P1': 1, 'P2': 2, 'P3': 3 }
        comparison = priorityOrder[a.priority as keyof typeof priorityOrder] - 
                    priorityOrder[b.priority as keyof typeof priorityOrder]
        break

      case 'dueDate':
        // 有日期的任务排在前面，按日期升序
        if (!a.dueDate && !b.dueDate) comparison = 0
        else if (!a.dueDate) comparison = 1
        else if (!b.dueDate) comparison = -1
        else comparison = new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime()
        break

      case 'createdAt':
        comparison = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
        break

      case 'title':
        comparison = a.title.localeCompare(b.title, 'zh-CN')
        break

      case 'status':
        // 未完成的任务排在前面
        comparison = (a.completed ? 1 : 0) - (b.completed ? 1 : 0)
        break

      default:
        comparison = 0
    }

    return direction === 'desc' ? -comparison : comparison
  })

  return sortedTasks
}

// 获取筛选条件的显示文本
export function getFilterDisplayText(filters: FilterOptions): string {
  const activeFilters: string[] = []

  // 优先级
  if (filters.priorities.length > 0 && filters.priorities.length < 4) {
    activeFilters.push(`优先级: ${filters.priorities.join(', ')}`)
  }

  // 分类
  if (filters.categories.length > 0 && filters.categories.length < 5) {
    const categoryLabels = {
      work: '工作', personal: '个人', learning: '学习', 
      health: '健康', other: '其他'
    }
    const labels = filters.categories.map(cat => 
      categoryLabels[cat as keyof typeof categoryLabels]
    )
    activeFilters.push(`分类: ${labels.join(', ')}`)
  }

  // 状态
  if (filters.statuses.includes('completed') && !filters.statuses.includes('pending')) {
    activeFilters.push('仅已完成')
  } else if (filters.statuses.includes('pending') && !filters.statuses.includes('completed')) {
    activeFilters.push('仅未完成')
  }

  // 标签
  if (filters.tags.length > 0) {
    activeFilters.push(`标签: ${filters.tags.join(', ')}`)
  }

  // 日期范围
  const dateRangeLabels = {
    today: '今天',
    thisWeek: '本周',
    overdue: '已过期',
    noDate: '无日期',
    all: '全部'
  }
  if (filters.dateRange !== 'all') {
    activeFilters.push(`时间: ${dateRangeLabels[filters.dateRange as keyof typeof dateRangeLabels]}`)
  }

  return activeFilters.length > 0 ? activeFilters.join(' | ') : '无筛选'
}

// 获取排序选项的显示文本
export function getSortDisplayText(sortBy: SortOption, direction: SortDirection): string {
  const sortLabels = {
    priority: '优先级',
    dueDate: '截止日期',
    createdAt: '创建时间',
    title: '标题',
    status: '完成状态'
  }

  const directionLabel = direction === 'asc' ? '升序' : '降序'
  return `${sortLabels[sortBy]} (${directionLabel})`
}
